package com.luck.email;

import com.sun.org.apache.regexp.internal.RE;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Map;

import static com.luck.email.MailConfig.FROM_MAIL;

/**
 * Created by Hua wb on 2018/12/19.
 */
@Component
public class MailService implements MailApi{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JavaMailSender mailSender;

    @Resource
    private FreeMarkerConfigurer configurer;

    @Resource
    private TemplateEngine templateEngine;

    @Override
    public void sendMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(FROM_MAIL);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        try {
            mailSender.send(message);
            logger.info("-----email-----普通邮件发送成功.");
        } catch (Exception e) {
            logger.error("-----email-----普通邮件发送异常:", e);
        }

    }

    @Override
    public void sendMail(EmailInfo emailInfo) {
        String templatePath = emailInfo.getTemplatePath();
        if (templatePath == null) {
            sendMail(emailInfo.getTo(), emailInfo.getSubject(), emailInfo.getContent());
        } else {
            sendMailTemplate(emailInfo.getTo(), emailInfo.getSubject(), templatePath, emailInfo.getMap());
        }
    }

    @Override
    public void sendMail(String to, String subject, String content, String filePath, String imgPath, String imgId) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(FROM_MAIL);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (filePath != null && filePath.length() != 0) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
                helper.addAttachment(fileName, file);
            }
            if (imgPath != null && imgPath.length() != 0) {
                FileSystemResource res = new FileSystemResource(new File(imgPath));
                helper.addInline(imgId, res);
            }
            mailSender.send(message);
            logger.info("-----email------附件邮件发送成功.");
        } catch (MessagingException e) {
            logger.error("-----email-----附件邮件发送异常:", e);
        }
    }
    @Override
    public void sendMailTemplate(String to, String subject, String templateName, Map map){
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(FROM_MAIL);
            helper.setTo(to);
            helper.setSubject(subject);
            // 加载模板的几种方式:
            // 1. .ftl模板  如:templateName = test.ftl
            String text = this.templateFreeMarker("ftl/", templateName, map);
            // 2. .html模板 如:templateName = test
            // String text = this.templateEngine("ftl/", templateName, map);

            helper.setText(text, true);
            mailSender.send(message);
            logger.info("-----email-----模板邮件发送成功.");
        } catch (Exception e){
            e.printStackTrace();
            logger.info("-----email-----模板邮件发送失败.");
        }
    }
    private String templateFreeMarker(String path, String fileName, Map parameter){
        String text = null;
        try {
            Template emailTemplate = configurer.getConfiguration().getTemplate(path + fileName);
            text = FreeMarkerTemplateUtils.processTemplateIntoString(emailTemplate, parameter);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return text;
    }
    private String templateEngine(String path, String fileName, Map parameter){
        Context context = new Context();
        context.setVariables(parameter);
        return templateEngine.process(path + fileName, context);
    }
    @Override
    public void sendMailTemplate(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(FROM_MAIL);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            logger.info("-----email-----html邮件发送成功.");
        } catch (Exception e){
            e.printStackTrace();
            logger.info("-----email-----html邮件发送失败.");
        }
    }

}
